package com.envmonitor.application.service;

import com.envmonitor.domain.model.Device;
import com.envmonitor.domain.service.DeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class DeviceApplicationService {
    
    private final DeviceService deviceService;
    
    public List<Device> getAllDevices() {
        return deviceService.getAllDevices();
    }
    
    public Optional<Device> getDeviceById(Long id) {
        return deviceService.getDeviceById(id);
    }
    
    public List<Device> getDevicesByType(Device.DeviceType type) {
        return deviceService.getDevicesByType(type);
    }
    
    @Transactional
    public Device createDevice(Device device) {
        return deviceService.saveDevice(device);
    }
    
    @Transactional
    public Optional<Device> updateDevice(Long id, Device deviceDetails) {
        Optional<Device> deviceOpt = deviceService.getDeviceById(id);
        if (deviceOpt.isPresent()) {
            Device device = deviceOpt.get();
            device.setName(deviceDetails.getName());
            device.setSerialNumber(deviceDetails.getSerialNumber());
            device.setType(deviceDetails.getType());
            device.setLocation(deviceDetails.getLocation());
            device.setActive(deviceDetails.isActive());
            return Optional.of(deviceService.saveDevice(device));
        }
        return Optional.empty();
    }
    
    @Transactional
    public void deleteDevice(Long id) {
        deviceService.deleteDevice(id);
    }
    
    @Transactional
    public Optional<Device> toggleDeviceStatus(Long id) {
        Optional<Device> deviceOpt = deviceService.getDeviceById(id);
        if (deviceOpt.isPresent()) {
            Device device = deviceOpt.get();
            return deviceService.updateDeviceStatus(id, !device.isActive());
        }
        return Optional.empty();
    }
}